let host = 'cn-guangzhou.log.aliyuncs.com'
let project = 'web-moniter'
let logstore = 'web-monitor-store'
import userAgent from 'user-agent'

function getExtraData(){
    return {
        title: document.title,
        url: location.url,
        timestamp: Date.now(),
        userAgent: userAgent.parse(navigator.userAgent).name
    }
}

class SendTracker {
    constructor(){
        this.url = `http://${project}.${host}/logstores/${logstore}/track` // 上报的路径
        this.xhr = new XMLHttpRequest

    }
    send(data = {}){
        this.xhr.open('POST', this.url, true)
        let log = { ...getExtraData(), ...data }
        // 对象的值不能是数字
        for(let key in log){
            if(typeof log[key] === 'number'){
                log[key] = `${log[key]}`
            }
        }
        let body = JSON.stringify({ __logs__: [log] })
        console.log(log, 'log')
        this.xhr.setRequestHeader('Content-Type', 'application/json')
        this.xhr.setRequestHeader('x-log-apiversion', '0.6.0')
        this.xhr.setRequestHeader('x-log-bodyrawsize', body.length)

        this.xhr.onload = () => {
            console.log(this.xhr.response)
        }

        this.xhr.onerror = err => {
            console.log(err)
        }

        this.xhr.send(body)
    }
}

export default new SendTracker